package com.gin.kotlin.gf2gamecommunity.base.livedata

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingSource
import androidx.paging.cachedIn
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow

/**
 * 自带缓存的PagingData
 * @param D 数据类型
 * @param P 参数类型
 * @param scope CoroutineScope
 * @param pageSize Int
 * @param factory (P) -> PagingSource<Int, D>
 * @constructor
 */
class CachedPagingData<D : Any, P>(
    private val scope: CoroutineScope,
    private val pageSize: Int = 10,
    private val factory: (P) -> PagingSource<Int, D>,
) {

    private var pagingDataMap = hashMapOf<String, Flow<PagingData<D>>>()

    fun fetch(param: P) = pagingDataMap[param.toString()] ?: Pager(
        config = PagingConfig(pageSize = pageSize, initialLoadSize = pageSize),
        pagingSourceFactory = { factory(param) }
    ).flow.cachedIn(scope).also { pagingDataMap[param.toString()] = it }


    companion object {
        private val TAG = CachedPagingData::class.java.simpleName
    }
}